<template>
  <div :class="{ 'hidden': hidden }" class="pagination-container">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :background="background"
      :layout="layout"
      :page-sizes="pageSizes"
      :total="total"
      v-bind="$attrs"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts" name="slTablePagination">
import { computed, watch } from 'vue'
import { scrollTo } from '/@/utils/scrollto'

interface Props {
  total: number
  page?: number
  limit?: number
  pageCount?: number
  pageSizes?: number[]
  layout?: string
  background?: boolean
  autoScroll?: boolean
  hidden?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  page: 1,
  limit: 30,
  pageCount: 999,
  pageSizes: () => [1, 20, 50, 100, 500, 1000],
  layout: 'total, sizes, prev, pager, next, jumper',
  background: true,
  autoScroll: true,
  hidden: false
})

const emit = defineEmits(['update:page', 'update:limit', 'pagination'])

const currentPage = computed({
  get: () => props.page,
  set: (val: number) => emit('update:page', val)
})

const pageSize = computed({
  get: () => props.limit,
  set: (val: number) => emit('update:limit', val)
})

watch(() => props.pageCount, () => {
  if (props.pageCount <= 100) {
    return
  }
  if (props.pageSizes.length === 4) {
    props.pageSizes.push(props.pageCount)
  } else {
    props.pageSizes.splice(4, 1, props.pageCount)
  }
})

const handleSizeChange = (val: number) => {
  emit('pagination', { page: currentPage.value, limit: val })
  if (props.autoScroll) {
    scrollTo(0, 800)
  }
}

const handleCurrentChange = (val: number) => {
  emit('pagination', { page: val, limit: pageSize.value })
  if (props.autoScroll) {
    scrollTo(0, 800)
  }
}
</script>

<style scoped>
.pagination-container.hidden {
  display: none;
}
</style>

<style>
.pagination-container .el-pagination.is-background .el-pager li:not(.disabled) {
  background-color: #ffffff;
  color: #000000;
}

.pagination-container .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #3B58D4;
  color: #ffffff;
}

.pagination-container .el-pagination.is-background .btn-next,
.pagination-container .el-pagination.is-background .btn-prev {
  min-width: 24px;
}

.el-pagination .el-select .el-input .el-input__inner,
.el-pagination span:not([class*=suffix]),
.el-pagination__editor.el-input .el-input__inner {
  height: 24px !important;
  line-height: 24px !important;
  font-size: 12px;
}

.el-pager li,
.el-pagination.is-background .el-pager li,
.el-pagination button {
  height: 22px !important;
  line-height: 22px !important;
  margin-top: 2px !important;
  min-width: 22px !important;
}
</style>
